package com.phpxiu.app.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.phpxiu.app.adapter.LiveHistoryListAdapter;
import com.phpxiu.app.adapter.holder.LiveHistoryViewHolder;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.HistoryHost;
import com.phpxiu.app.model.LiveHistoryContent;
import com.phpxiu.app.model.list.LiveHistory;
import com.phpxiu.app.model.response.LiveHistoryModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.pulltorefresh.PullToRefreshListView;
import com.phpxiu.app.pulltorefresh.PullToRefreshView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.ListEmptyView;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户我的直播
 * Created by WuJinZhou on 2016/6/4.
 */
public class UserLiveHistory extends UIBase implements View.OnClickListener,AdapterView.OnItemClickListener,PullToRefreshView.OnRefreshListener2<ListView>{
    public final static String TAG="UserLiveHistory";
    public final static String UID="user_id";
    private final static int HANDLE_REFRESH_COMPLETE=0x1;
    private String uid;
    private List<LiveHistory> histories=new ArrayList<LiveHistory>();
    private PullToRefreshListView ptRefreshView;
    private ListView mListView;
    private LiveHistoryListAdapter mAdapter;
    private ListEmptyView emptyView;
    private int mOpera= HttpConfig.REQUEST_OPERA_INIT;
    private int pageSize=15;//每页取15条记录
    private int currentAllRecords=0;//当前列表刷新时获取的后台记录条数
    private int pageIndex=1;//下一页序号,页数从1开始计数
    private OKHttpParam param;
    private String dateDistanceYMD;
    private String dateDaysSuffix;
    private String dateHoursSuffix;
    private String dateMinuteSuffix;
    private String dateDefaultSuffix;
    private LiveHistoryContent baseContent=new LiveHistoryContent();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uid=getIntent().getStringExtra(UID);
        if(uid==null||"".equals(uid)){
            finish();
            return;
        }
        setContentView(R.layout.user_live_history);
        initDateSuffix();
        init();
    }

    /**
     * 初始化视图
     */
    private void init(){
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        emptyView=new ListEmptyView(this);
        emptyView.setMsg(getString(R.string.list_empty_title));
        ptRefreshView=(PullToRefreshListView)findViewById(R.id.live_history_pull_refresh_list);
        ptRefreshView.setOnRefreshListener(this);
        mListView=ptRefreshView.getRefreshableView();
        mListView.setOnItemClickListener(this);
        mListView.setEmptyView(emptyView);
        mListView.setDivider(null);
        mAdapter=new LiveHistoryListAdapter(this,histories);
        mAdapter.initDateSuffix(dateDistanceYMD,dateDaysSuffix,dateHoursSuffix,dateMinuteSuffix,dateDefaultSuffix);
        mListView.setAdapter(mAdapter);
        request(mOpera);
    }

    private void initDateSuffix(){
        dateDistanceYMD=getString(R.string.date_distance_ymd);
        dateDaysSuffix=getString(R.string.date_distance_day_ago);
        dateHoursSuffix=getString(R.string.date_distance_hour_ago);
        dateMinuteSuffix=getString(R.string.date_distance_minute_ago);
        dateDefaultSuffix=getString(R.string.date_distance_default);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            default:
                break;
        }
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLE_REFRESH_COMPLETE:
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                break;
        }
    }

    /**
     * 请求数据初始化
     */
    private void request(int opera){
        mOpera=opera;
        if(param==null){
            param=OKHttpParam.builder();
            param.put("pageSize",pageSize);
        }
        param.put("uid",uid);
        param.put("pageIndex",1);
        if(mOpera==HttpConfig.REQUEST_OPERA_LOAD){
            param.put("pageIndex",pageIndex==1?2:pageIndex);
        }
        OKHttp.post(HttpConfig.API_USER_HISTORY_LIST, param.jsonParam(), TAG, new OKHttpUIHandler(LiveHistoryModel.class) {
            @Override
            public void onSuccess(Object model) {
                emptyView.loaded();
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                try {
                    LiveHistoryModel m = (LiveHistoryModel) model;
                    KKYUtil.log(TAG, "我的历史直播：" + m.getResponseStr());
                    if (mOpera == HttpConfig.REQUEST_OPERA_REFRESH || mOpera == HttpConfig.REQUEST_OPERA_INIT) {
                        histories.clear();
                        HistoryHost host = m.getData().getHost();
                        baseContent.setHostId(host.getUid());
                        baseContent.setLiveNo(host.getUid());
                        baseContent.setNick(host.getNickname());
                        baseContent.setAvatar(host.getAvatar());
                        baseContent.setTickets(host.getTotal_income());
                        currentAllRecords = m.getData().getTotalItem();
                        pageIndex = 1;
                    } else {
                        if (currentAllRecords > 0 && histories.size() > 0 && histories.size() < currentAllRecords) {
                            pageIndex++;
                        }
                    }
                    histories.addAll(m.getData().getVideolist());
                    mAdapter.notifyDataSetChanged();
                    listEmpty(histories.size() == 0);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onErr(String errMsg) {
                if (ptRefreshView != null) {
                    ptRefreshView.onRefreshComplete();
                }
                listEmpty(histories.size() == 0);
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(view.getTag()!=null&&view.getTag() instanceof LiveHistoryViewHolder){
            LiveHistory history=((LiveHistoryViewHolder)view.getTag()).getHistory();
            Intent play=new Intent(this, UIHistoryVideoPlayer.class);
            baseContent.setLiveTitle(history.getTitle());
            baseContent.setVideoUrl(history.getUrl());
            baseContent.setWatchCount(history.getViewed());
            play.putExtra(UIHistoryVideoPlayer.LIVE_INFO,baseContent);
            startActivity(play);
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshView<ListView> refreshView) {
        request(HttpConfig.REQUEST_OPERA_REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshView<ListView> refreshView) {
        if(histories.size()!=0&&histories.size()<currentAllRecords) {
            request(HttpConfig.REQUEST_OPERA_LOAD);
        }else{
            handler.sendEmptyMessage(HANDLE_REFRESH_COMPLETE);
        }
    }

    /**
     * 空列表,不加载更多
     */
    public void listEmpty(boolean isEmpty){
        if (ptRefreshView != null) {
            if(isEmpty) {
                ptRefreshView.setMode(PullToRefreshView.Mode.PULL_FROM_START);
            }else{
                ptRefreshView.setMode(PullToRefreshView.Mode.BOTH);
            }
        }
    }
}
